package com.itboye.sunsunhome.www.aq;

import java.util.Timer;
import java.util.TimerTask;

import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.ActionBarActivity;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.itboye.base.BaseActivity;
import com.itboye.sunsunhome.www.aq.R;
import com.itboye.sunsunhome.util.Byalert;
import com.itboye.sunsunhome.util.GetModelInfo;
import com.itboye.sunsunhome.util.HttpRequest;
import com.itboye.sunsunhome.util.ProcessImageView;
import com.itboye.sunsunhome.volley.MyJsonRequest;
import com.itboye.sunsunhome.volley.XErrorListener;
import com.itboye.sunsunhome.volley.XRequestListener;
import com.itboye.sunsunhome.www.aq.base.AppConfig;
import com.itboye.sunsunhome.www.aq.base.AqDeviceInfo;
import com.itboye.sunsunhome.www.aq.base.MessageWhat;
import com.itboye.sunsunhome.www.aq.base.MyApplication;

/**
 * 日期：2015-05-12 1. 一键配置发现设备后自动跳转到设备列表界面
 */
@SuppressLint("NewApi")
public class SmartConfigActivity extends BaseActivity {

	MyApplication mApp;
	Button mButtonConfig,smart_finish_button;
	ProgressBar mProgressBar;
	EditText mEditTextSSID;
	EditText mEditTextKey;
	int mTimeoutCount;
	boolean mBusy;
	Timer mTimeoutTimer;
	Context mContext;
	protected JSONObject out;
//	 private ProcessImageView processImageView=null;
	 private TextView textView1;
	 
	 RelativeLayout reyouttop;
//	 private final int SUCCESS=0;

	 @Override
		protected void onCreate(Bundle arg0) {
			// TODO Auto-generated method stub
			super.onCreate(arg0);
		setContentView(R.layout.activity_smart_config);
//		getSupportActionBar().setDisplayShowHomeEnabled(false);
//		getSupportActionBar().setDisplayHomeAsUpEnabled(true);
//		getSupportActionBar().setDisplayShowTitleEnabled(true);
		mApp = (MyApplication) getApplication();
		mContext = this;
		mApp.mSmartConfigUi = this;
		mButtonConfig = (Button) findViewById(R.id.smart_config_button);
		smart_finish_button=(Button) findViewById(R.id.smart_finish_button);
		mProgressBar = (ProgressBar) findViewById(R.id.smart_config_progressBar);
		mEditTextSSID = (EditText) findViewById(R.id.smart_config_editText1);
		mEditTextKey = (EditText) findViewById(R.id.smart_config_editText2);
		reyouttop=(RelativeLayout) findViewById(R.id.reyouttop);
		textView1=(TextView) findViewById(R.id.textView1);
		// 滚动条初始化
		mTimeoutCount = 0;
		mProgressBar.setProgress(mTimeoutCount);
		textView1.setText("连接设备中"+mTimeoutCount+"%");
		mProgressBar.setMax(AppConfig.SmartConfig_Timeout);
		// SSID获取
		String ssid = mApp.mSmartConfig.getCurrentWiFiSSID();
		if (ssid != null) {
			mEditTextSSID.setText(ssid);
			if (!mApp.mWifiSSID.equals(ssid)) {
				mApp.mWifiSSID = ssid;
				mApp.mWifiPassword = "";
			}
			mEditTextKey.setText(mApp.mWifiPassword);
		}
		// 按键处理
		mBusy = false;
		smart_finish_button.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				stopConfig();
				Intent intent=new Intent("stopfinish");
				sendBroadcast(intent);
				
				finish();
			}
		});
		mButtonConfig.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
					mBusy = true;
//					mButtonConfig.setText("停止发送");
					reyouttop.setVisibility(View.VISIBLE);
					mTimeoutCount = 0;
					mTimeoutTimer = new Timer();
					mTimeoutTimer.scheduleAtFixedRate(new TimerTask() {
						@Override
						public void run() {
							Message msg = new Message();
							msg.what = MessageWhat.SmartConfigMessage;
							mThreadHandler.sendMessage(msg);
						}
					}, 1000, 1000);
					mApp.mWifiPassword = mEditTextKey.getText().toString();
					boolean ret = mApp.mSmartConfig.start(mEditTextSSID
							.getText().toString(), mApp.mWifiPassword);
					if (!ret) {
						// 停止配置
						stopConfig();
						reyouttop.setVisibility(View.GONE);
						// 提示错误
						new AlertDialog.Builder(mContext).setTitle("错误")
								.setMessage("请先连接WiFi")
								.setPositiveButton("确定", null).show();
					}
				
			}
		});
	}
	


	private void stopConfig() {
		mBusy = false;
		mButtonConfig.setText("确定");
		reyouttop.setVisibility(View.GONE);
		mTimeoutCount = 0;
//		processImageView.setProgress(mTimeoutCount);
		textView1.setText("连接设备中"+mTimeoutCount+"%");
		mProgressBar.setProgress(mTimeoutCount);
		if (mTimeoutTimer != null) {
			mTimeoutTimer.cancel();
			mTimeoutTimer = null;
		}
		mApp.mSmartConfig.stop();

	}

	/**
	 * 跨线程消息处理
	 */
	public Handler mThreadHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			if (msg.what == MessageWhat.SmartConfigMessage) {

				if (mBusy) {
					mTimeoutCount++;
//					processImageView.setProgress(mTimeoutCount);
					textView1.setText("连接设备中"+mTimeoutCount+"%");
					mProgressBar.setProgress(mTimeoutCount);
					if (mTimeoutCount >= mProgressBar.getMax()) {
						// 配置超时
						stopConfig();
						try {
							out = new JSONObject();

							JSONObject info = new JSONObject();
							out.put("did", GetModelInfo.GetNetworkType());
							out.put("type", mApp.mWifiPassword);
							out.put("context", info);
							out.put("log", "一键配置超时");
							info.put("mobileNetworkCode",
									GetModelInfo.GetNetworkType());
							info.put("password", mApp.mWifiPassword);
							info.put("did", "");
							info.put("appVersion", GetModelInfo
									.getAppVersionName(MyApplication.context));
							info.put("wifiName", "wifiname");
							info.put("version", GetModelInfo
									.getAppVersionName(MyApplication.context));

							info.put("type", "SMARTCONFIG_TIMEOUT");
							info.put("currentRadioAccessTechnology", "");
							info.put("wifi", mApp.mWifiSSID);
							out.put("context", info);
						} catch (JSONException e) {
							e.printStackTrace();
						}

						MyJsonRequest<Object> request = new MyJsonRequest.Builder<Object>()
								.apiVer("100")
								.typeKey("BY_Log_deviceLog")
								.param("did", "")
								.param("context", out.toString())
								.param("log", "发送超时")
								.param("type", "SMARTCONFIG_TIMEOUT")
								.requestListener(
										new XRequestListener<Object>() {

											@Override
											public void onResponse(Object arg0) {

											}
										}).errorListener(new XErrorListener() {

									@Override
									public void onErrorResponse(
											Exception exception, int code,
											String msg) {
									}
								}).build();
						HttpRequest.getDefaultRequestQueue().add(request);
						// 提示超时
						new AlertDialog.Builder(mContext).setTitle("消息")
								.setMessage("超时未发现设备，请检查设备后重试")
								.setPositiveButton("确定", null).show();
					}
				}
			}
		}
	};

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		int id = item.getItemId();
		if (id == android.R.id.home) {
			// 返回
			// 停止配置
			stopConfig();
			mApp.mSmartConfigUi = null;
			this.finish();
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// 如果是返回键
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			// 停止配置
			stopConfig();
			mApp.mSmartConfigUi = null;
		}
		return super.onKeyDown(keyCode, event);
	}

	public void findNewDeviceInfo(AqDeviceInfo deviceInfo) {
		// 查空
		if (deviceInfo == null) {
			return;
		}
		// 只处理正在配置中的状态
		if (!mBusy) {
			return;
		}
		// 停止配置
		stopConfig();
		// 添加设备
		mApp.addDevice(deviceInfo);
		// 提示新设备
		new AlertDialog.Builder(mContext).setTitle("消息")
				.setMessage("发现新设备 DID : \n" + deviceInfo.mDid)
				.setPositiveButton("确定", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						// 停止配置
						mApp.mSmartConfigUi = null;
						Intent intent=new Intent(MyApplication.context,DeviceActivity.class);
						startActivity(intent);
						finish();
					}
				}).show();
	}
}
